package mgodb

import (
	"github.com/facebookgo/inject"
	"github.com/globalsign/mgo"
	"github.com/globalsign/mgo/bson"
	"jgt-oper/src/model"
	"jgt-oper/src/schema"
	"jgt-oper/src/service/mongo"
)

// cParkEntrance 门牌和门禁设备对应关系表
const cParkEntrance = "oper_park_entrance"

// ParkEntrance 门牌和门禁设备对应关系管理
type ParkEntrance struct {
	DB *mongo.DB
}

// Init 初始化
func (a *ParkEntrance) Init(g *inject.Graph, db *mongo.DB) {
	a.DB = db

	// 初始化mongo索引
	a.DB.C(cParkEntrance, func(c *mgo.Collection) error {
		c.EnsureIndex(mgo.Index{
			Key:    []string{"node_id", "deleted"},
			Unique: true,
		})
		c.EnsureIndexKey("node_id")
		return nil
	})

	var val model.IParkEntrance = a
	g.Provide(&inject.Object{Value: val, Name: "IParkEntrance"})
}

// Create 创建数据条目
func (a *ParkEntrance) Create(item *schema.ParkEntrance) error {
	// TODO
	return nil
}

// Get 查询
func (a *ParkEntrance) Get(nodeID string) (*schema.ParkEntrance, error) {
	return nil, nil
}

// Delete 删除
func (a *ParkEntrance) Delete(nodeID string) error {
	return nil
}

// AddEntrance 添加门牌
func (a *ParkEntrance) AddEntrance(nodeID string, entrances []string) error {
	return nil
}

// DeleteEntrance 删除门牌
func (a *ParkEntrance) DeleteEntrance(nodeID string, entrance []string) error {
	return nil
}

// GetByArray 批量查询门牌和门禁设备对应关系
func (a *ParkEntrance) GetByArray(nodeArray []string) ([]*schema.ParkEntrance, error) {
	query := bson.M{
		"deleted": 0,
		"node_id": bson.M{"$in": nodeArray},
	}

	var items []*schema.ParkEntrance
	err := a.DB.C(cParkEntrance, func(c *mgo.Collection) error {
		return c.Find(query).All(&items)
	})
	if err != nil {
		return nil, err
	}

	return items, nil
}

// GetByEntranceID 根据门禁设备查询所有的门牌和门禁设备对应关系
func (a ParkEntrance) GetByEntranceID(entranceID string) ([]*schema.ParkEntrance, error) {
	query := bson.M{
		"deleted":   0,
		"entrances": entranceID,
	}

	var items []*schema.ParkEntrance
	err := a.DB.C(cParkEntrance, func(c *mgo.Collection) error {
		return c.Find(query).All(&items)
	})
	if err != nil {
		return nil, err
	}
	return items, nil
}
